#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
账号管理器
负责账号的创建、登录和管理
"""

import hashlib
import logging
from datetime import datetime
from typing import Optional, Tuple, List, Dict, Any
from database import db_manager, Account

class AccountManager:
    """
    账号管理器
    """
    
    def __init__(self):
        """
        初始化账号管理器
        """
        self.current_account: Optional[Account] = None
        self.logger = logging.getLogger(__name__)
        
        # 测试数据库连接
        if not db_manager.test_connection():
            raise Exception("数据库连接失败")
    
    def create_account(self, username: str, email: str, password: str) -> Tuple[bool, str, Optional[Account]]:
        """
        创建新账号
        
        Args:
            username: 用户名
            email: 邮箱
            password: 密码
            
        Returns:
            (成功标志, 消息, 账号对象)
        """
        try:
            # 验证输入
            if not username or len(username) < 3:
                return False, "用户名至少需要3个字符", None
            
            if not email or '@' not in email:
                return False, "请输入有效的邮箱地址", None
            
            if not password or len(password) < 6:
                return False, "密码至少需要6个字符", None
            
            # 检查用户名是否已存在
            if self.get_account_by_username(username):
                return False, f"用户名 '{username}' 已存在", None
            
            # 检查邮箱是否已存在
            if self.get_account_by_email(email):
                return False, f"邮箱 '{email}' 已被注册", None
            
            # 创建密码哈希
            password_hash = self._hash_password(password)
            
            # 插入账号记录
            now = datetime.now()
            insert_query = """
                INSERT INTO accounts (username, email, password_hash, created_at, last_login, status)
                VALUES (%s, %s, %s, %s, %s, %s)
            """
            
            account_id = db_manager.execute_insert(insert_query, (
                username, email, password_hash, now, now, 'active'
            ))
            
            # 获取创建的账号
            account = self.get_account_by_id(account_id)
            
            self.logger.info(f"账号 '{username}' 创建成功，ID: {account_id}")
            return True, f"账号 '{username}' 创建成功", account
            
        except Exception as e:
            self.logger.error(f"创建账号失败: {e}")
            return False, f"创建账号失败: {str(e)}", None
    
    def login(self, username: str, password: str) -> Tuple[bool, str, Optional[Account]]:
        """
        账号登录
        
        Args:
            username: 用户名
            password: 密码
            
        Returns:
            (成功标志, 消息, 账号对象)
        """
        try:
            # 获取账号
            account = self.get_account_by_username(username)
            if not account:
                return False, "用户名或密码错误", None
            
            # 检查账号是否激活
            if not account.is_active:
                return False, "账号已被禁用", None
            
            # 验证密码
            if not self._verify_password(password, account.password_hash):
                return False, "用户名或密码错误", None
            
            # 更新最后登录时间
            self._update_last_login(account.account_id)
            account.last_login = datetime.now()
            
            # 设置当前账号
            self.current_account = account
            
            self.logger.info(f"账号 '{username}' 登录成功")
            return True, f"欢迎回来，{username}！", account
            
        except Exception as e:
            self.logger.error(f"登录失败: {e}")
            return False, f"登录失败: {str(e)}", None
    
    def logout(self) -> bool:
        """
        账号登出
        
        Returns:
            是否成功
        """
        if self.current_account:
            username = self.current_account.username
            self.current_account = None
            self.logger.info(f"账号 '{username}' 已登出")
            return True
        return False
    
    def get_account_by_id(self, account_id: int) -> Optional[Account]:
        """
        根据ID获取账号
        
        Args:
            account_id: 账号ID
            
        Returns:
            账号对象或None
        """
        try:
            query = "SELECT * FROM accounts WHERE id = %s"
            result = db_manager.execute_query(query, (account_id,))
            
            if result:
                return Account.from_dict(result[0])
            
            return None
            
        except Exception as e:
            self.logger.error(f"获取账号失败: {e}")
            return None
    
    def get_account_by_username(self, username: str) -> Optional[Account]:
        """
        根据用户名获取账号
        
        Args:
            username: 用户名
            
        Returns:
            账号对象或None
        """
        try:
            query = "SELECT * FROM accounts WHERE username = %s"
            result = db_manager.execute_query(query, (username,))
            
            if result:
                return Account.from_dict(result[0])
            
            return None
            
        except Exception as e:
            self.logger.error(f"获取账号失败: {e}")
            return None
    
    def get_account_by_email(self, email: str) -> Optional[Account]:
        """
        根据邮箱获取账号
        
        Args:
            email: 邮箱
            
        Returns:
            账号对象或None
        """
        try:
            query = "SELECT * FROM accounts WHERE email = %s"
            result = db_manager.execute_query(query, (email,))
            
            if result:
                return Account.from_dict(result[0])
            
            return None
            
        except Exception as e:
            self.logger.error(f"获取账号失败: {e}")
            return None
    
    def update_password(self, account_id: int, old_password: str, new_password: str) -> Tuple[bool, str]:
        """
        更新密码
        
        Args:
            account_id: 账号ID
            old_password: 旧密码
            new_password: 新密码
            
        Returns:
            (成功标志, 消息)
        """
        try:
            # 获取账号
            account = self.get_account_by_id(account_id)
            if not account:
                return False, "账号不存在"
            
            # 验证旧密码
            if not self._verify_password(old_password, account.password_hash):
                return False, "旧密码错误"
            
            # 验证新密码
            if len(new_password) < 6:
                return False, "新密码至少需要6个字符"
            
            # 更新密码
            new_password_hash = self._hash_password(new_password)
            update_query = "UPDATE accounts SET password_hash = %s WHERE id = %s"
            
            affected_rows = db_manager.execute_update(update_query, (new_password_hash, account_id))
            
            if affected_rows > 0:
                self.logger.info(f"账号 {account.username} 密码已更新")
                return True, "密码更新成功"
            else:
                return False, "密码更新失败"
                
        except Exception as e:
            self.logger.error(f"更新密码失败: {e}")
            return False, f"更新密码失败: {str(e)}"
    
    def deactivate_account(self, account_id: int) -> Tuple[bool, str]:
        """
        禁用账号
        
        Args:
            account_id: 账号ID
            
        Returns:
            (成功标志, 消息)
        """
        try:
            update_query = "UPDATE accounts SET status = 'inactive' WHERE id = %s"
            affected_rows = db_manager.execute_update(update_query, (account_id,))
            
            if affected_rows > 0:
                # 如果禁用的是当前账号，登出
                if self.current_account and self.current_account.account_id == account_id:
                    self.logout()
                
                self.logger.info(f"账号 ID {account_id} 已禁用")
                return True, "账号已禁用"
            else:
                return False, "禁用失败"
                
        except Exception as e:
            self.logger.error(f"禁用账号失败: {e}")
            return False, f"禁用账号失败: {str(e)}"
    
    def get_account_stats(self) -> Dict[str, Any]:
        """
        获取账号统计信息
        
        Returns:
            统计信息字典
        """
        try:
            # 总账号数
            total_query = "SELECT COUNT(*) as total FROM accounts"
            total_result = db_manager.execute_query(total_query)
            total_accounts = total_result[0]['total'] if total_result else 0
            
            # 活跃账号数
            active_query = "SELECT COUNT(*) as active FROM accounts WHERE status = 'active'"
            active_result = db_manager.execute_query(active_query)
            active_accounts = active_result[0]['active'] if active_result else 0
            
            # 今日注册数
            today_query = "SELECT COUNT(*) as today FROM accounts WHERE DATE(created_at) = CURDATE()"
            today_result = db_manager.execute_query(today_query)
            today_registrations = today_result[0]['today'] if today_result else 0
            
            return {
                'total_accounts': total_accounts,
                'active_accounts': active_accounts,
                'inactive_accounts': total_accounts - active_accounts,
                'today_registrations': today_registrations,
                'current_account': self.current_account.username if self.current_account else None
            }
            
        except Exception as e:
            self.logger.error(f"获取统计信息失败: {e}")
            return {
                'total_accounts': 0,
                'active_accounts': 0,
                'inactive_accounts': 0,
                'today_registrations': 0,
                'current_account': None
            }
    
    def _hash_password(self, password: str) -> str:
        """
        生成密码哈希
        
        Args:
            password: 原始密码
            
        Returns:
            密码哈希
        """
        # 使用SHA-256哈希（实际项目中应使用更安全的方法如bcrypt）
        return hashlib.sha256(password.encode('utf-8')).hexdigest()
    
    def _verify_password(self, password: str, password_hash: str) -> bool:
        """
        验证密码
        
        Args:
            password: 原始密码
            password_hash: 存储的密码哈希
            
        Returns:
            是否匹配
        """
        return self._hash_password(password) == password_hash
    
    def _update_last_login(self, account_id: int):
        """
        更新最后登录时间
        
        Args:
            account_id: 账号ID
        """
        try:
            update_query = "UPDATE accounts SET last_login = %s WHERE id = %s"
            db_manager.execute_update(update_query, (datetime.now(), account_id))
        except Exception as e:
            self.logger.error(f"更新登录时间失败: {e}")
    
    def register(self, username: str, password: str, email: str = '') -> Optional[Account]:
        """
        注册新账号（为了兼容Flask应用的简化接口）
        
        Args:
            username: 用户名
            password: 密码
            email: 邮箱（可选）
            
        Returns:
            账号对象或None
        """
        # 如果没有提供邮箱，使用默认格式
        if not email:
            email = f"{username}@example.com"
        
        success, message, account = self.create_account(username, email, password)
        return account if success else None
    

    
    def is_logged_in(self) -> bool:
        """
        检查是否已登录
        
        Returns:
            是否已登录
        """
        return self.current_account is not None
    
    def get_current_account_id(self) -> Optional[int]:
        """
        获取当前账号ID
        
        Returns:
            当前账号ID或None
        """
        return self.current_account.account_id if self.current_account else None